<?php

use think\Cache;
use think\Db;

/**
 * 获取来源名称
 */
function getPlayerNames()
{
    $player_list = config('vodplayer');
    return $player_list;
}

/**
 * 获取线路
 */
function getVodServer()
{
    $server_list = config('vodserver');
    return $server_list;
}

/**
 * 获取发行地区
 * @return false|string[]
 */
function getArea()
{
    $config = config('maccms.app');
    $area_list = explode(',', $config['vod_area']);
    return $area_list;
}

/**
 * 获取对白语言
 * @return false|string[]
 */
function getLang()
{
    $config = config('maccms.app');
    $lang_list = explode(',', $config['vod_lang']);
    return $lang_list;
}

/**
 * 得到分类的扩展信息
 * @param $id
 * @return array
 */
function getTypeExtend($id, $useParent = false)
{
    $type_list = model('Type')->getCache('type_list');
    $type_info = $type_list[$id];
//        dump($type_info);
    if (!empty($type_info)) {
        $type_mid = $type_info['type_mid'];
        $type_pid = $type_info['type_pid'];
        $type_pinfo = $type_list[$type_pid];
        $type_extend = $type_info['type_extend'];
        $type_pextend = $type_pinfo['type_extend'];

        if ($useParent) {
            $config = config('maccms.app');

            if ($type_mid == 2) {
                if (empty($type_extend['class']) && !empty($type_pextend['class'])) {
                    $type_extend['class'] = $type_pextend['class'];
                } elseif (empty($type_extend['class']) && !empty($config['art_extend_class'])) {
                    $type_extend['class'] = $config['art_extend_class'];
                }
            } else {
                if (empty($type_extend['class']) && !empty($type_pextend['class'])) {
                    $type_extend['class'] = $type_pextend['class'];
                } elseif (empty($type_extend['class']) && !empty($config['vod_extend_class'])) {
                    $type_extend['class'] = $config['vod_extend_class'];
                }

                if (empty($type_extend['state']) && !empty($type_pextend['state'])) {
                    $type_extend['state'] = $type_pextend['state'];
                } elseif (empty($type_extend['state']) && !empty($config['vod_extend_state'])) {
                    $type_extend['state'] = $config['vod_extend_state'];
                }

                if (empty($type_extend['version']) && !empty($type_pextend['version'])) {
                    $type_extend['version'] = $type_pextend['version'];
                } elseif (empty($type_extend['version']) && !empty($config['vod_extend_version'])) {
                    $type_extend['version'] = $config['vod_extend_version'];
                }

                if (empty($type_extend['area']) && !empty($type_pextend['area'])) {
                    $type_extend['area'] = $type_pextend['area'];
                } elseif (empty($type_extend['area']) && !empty($config['vod_extend_area'])) {
                    $type_extend['area'] = $config['vod_extend_area'];
                }

                if (empty($type_extend['lang']) && !empty($type_pextend['lang'])) {
                    $type_extend['lang'] = $type_pextend['lang'];
                } elseif (empty($type_extend['lang']) && !empty($config['vod_extend_lang'])) {
                    $type_extend['lang'] = $config['vod_extend_lang'];
                }

                if (empty($type_extend['year']) && !empty($type_pextend['year'])) {
                    $type_extend['year'] = $type_pextend['year'];
                } elseif (empty($type_extend['year']) && !empty($config['vod_extend_year'])) {
                    $type_extend['year'] = $config['vod_extend_year'];
                }
            }
        }
        if (!empty($type_extend)) {
            foreach ($type_extend as $key => $value) {
                $options = explode(',', $value);
                $extend[$key] = array_filter($options);
            }
        }

        return $extend;
    }
    return [];
}

function listAppData(
    $where,
    $order,
    $page = 1,
    $limit = 20,
    $start = 0,
    $field = '*',
    $addition = 1,
    $totalshow = 1,
    $whereRaw = []
)
{
    if (!is_array($where)) {
        $where = json_decode($where, true);
    }
    if (!isset($where['vod_status'])) {
        $where['vod_status'] = 1;//确保视频数据为已审核
    }
//        dump($where);
    $limit_str = ($limit * ($page - 1) + $start) . "," . $limit;
    if ($totalshow == 1) {
        $total = db('Vod')->where($where)->whereRaw($whereRaw)->count();
    }

    $list = db('Vod')->field($field)->where($where)->whereRaw($whereRaw)->orderRaw($order)->limit($limit_str)->select();
//        dump($list);
//            dump(db('Vod')->getLastSql());
//        exit;
    //分类
    $type_list = model('Type')->getCache('type_list');
    $playNames = getPlayerNames();
    foreach ($list as &$v) {
        $v['vod_pic'] = strpos($v['vod_pic'], 'http') === 0 ? $v['vod_pic'] : (request()->domain() . '/' . $v['vod_pic']);
        $v['vod_pic_thumb'] = $v['vod_pic_thumb'] ? (strpos(
            $v['vod_pic_thumb'],
            'http'
        ) === 0 ? $v['vod_pic_thumb'] : (request()->domain() . '/' . $v['vod_pic_thumb'])) : '';
        $v['vod_pic_slide'] = $v['vod_pic_slide'] ? (strpos(
            $v['vod_pic_slide'],
            'http'
        ) === 0 ? $v['vod_pic_slide'] : (request()->domain() . '/' . $v['vod_pic_slide'])) : '';

        $v['vod_time_text'] = date('Y-m-d H:i', $v['vod_time']);
        if ($addition == 1) {
            if (!empty($v['type_id'])) {
                $v['type'] = $type_list[$v['type_id']];
                $v['type_1'] = $type_list[$v['type']['type_pid']];
            }
            //处理数据
            $v['vod_tag'] = explode(',', $v['vod_tag']);
            $v['vod_actor'] = explode(',', $v['vod_actor']);
            $playGroups = [];
            $playfroms = explode('$$$', $v['vod_play_from']);
            unset($v['vod_play_from']);
            $playNotes = explode('$$$', $v['vod_play_note']);
            unset($v['vod_play_note']);
            unset($v['vod_play_server']);
            $playUrls = explode('$$$', $v['vod_play_url']);
            unset($v['vod_play_url']);
            foreach ($playUrls as $key => $jujiurl) {
                //解析url
                $jujis = explode('#', $jujiurl);
                $playList = [];
                foreach ($jujis as $juji) {
                    list($name, $url) = explode('$', $juji);
                    $playList[] = [
                        'name' => $name,
                        'url' => $url
                    ];
                }
                $playGroups[$key] = [
                    'playlist' => $playList,
                    'from' => $playNames[$playfroms[$key]],
                    'note' => $playNotes[$key]
                ];
            }
            $v['play_group'] = $playGroups;
        }

        if (isset($v['image_down']) && $v['image_down'] > 0) {
            $v['vod_pic'] = "http://7dfjeh.aojiasen.cn/cover/" . $v['vod_id'] . '.jpg';
        }
    }
    return [
        'page' => $page,
        'pagecount' => ceil($total / $limit),
        'limit' => $limit,
        'total' => $total,
        'list' => $list
    ];
}

function getVodByIdDetailtwo($id)
{
    $v = Db::name('Vod')->where('vod_id', $id)->where('vod_status', 1)->find();
    if (empty($v)) {
        return [];
    }
    $v['playNames'] = getPlayerNames();
    $v['vod_time'] = date('Y-m-d H:i', $v['vod_time']);
    $v['vod_pic'] = strpos($v['vod_pic'], 'http') === 0 ? $v['vod_pic'] : (request()->domain() . '/' . $v['vod_pic']);

    $v['vod_content'] = strip_tags($v['vod_content']);
    $v['vod_pic_thumb'] = $v['vod_pic_thumb'] ? (strpos(
        $v['vod_pic_thumb'],
        'http'
    ) === 0 ? $v['vod_pic_thumb'] : (request()->domain() . '/' . $v['vod_pic_thumb'])) : '';
    $v['vod_actor'] = explode(',', $v['vod_actor']);
    $v['ism3u8'] = 1;
    $v['fileurl'] = [];
    if ($v['is_cache'] == 1) {
        $sortOrder = 'asc';
        if (in_array($v['type_id_1'], [3])) {
            $sortOrder = 'desc';
        }
        $v['fileurl'] = \db('m3u8_cache')->fieldRaw('sort as `index`, CASE WHEN cache_value is not null THEN cache_value ELSE `value` END as url, `key` as name,1 as ism3u8 ')->where('vod_id', $v['vod_id'])->order('sort', $sortOrder)->select();
        foreach ($v['fileurl'] as $key => &$juji) {
            $juji['index'] = $key;
        }
//            dump(\db()->getLastSql());exit;
    }
    return $v;
}

function getVodByIdDetailtest($id)
{
    $v = Db::name('Vod')->where('vod_id', $id)->where('vod_status', 1)->find();
    if (empty($v)) {
        return [];
    }
    $v['playNames'] = getPlayerNames();
    $v['vod_time'] = date('Y-m-d H:i', $v['vod_time']);
    $v['vod_pic'] = strpos($v['vod_pic'], 'http') === 0 ? $v['vod_pic'] : (request()->domain() . '/' . $v['vod_pic']);

    $v['vod_content'] = strip_tags($v['vod_content']);
    $v['vod_pic_thumb'] = $v['vod_pic_thumb'] ? (strpos(
        $v['vod_pic_thumb'],
        'http'
    ) === 0 ? $v['vod_pic_thumb'] : (request()->domain() . '/' . $v['vod_pic_thumb'])) : '';
    $v['vod_actor'] = explode(',', $v['vod_actor']);
    $v['ism3u8'] = 1;
    $v['fileurl'] = [];
    if (!empty($v['is_cache'])) {
        $dir = $_SERVER['DOCUMENT_ROOT'] . "/upload/m3u8/" . $id;
        if (is_dir($dir)) {
            $fileArr = [];
            if ($dh = opendir($dir)) {
                while (($file = readdir($dh)) != false) {
                    //文件名的全路径 包含文件名
                    if (strstr($file, ".m3u8") !== false) {
                        $filePath = 'https://' . $_SERVER['HTTP_HOST'] . "/upload/m3u8/" . $id . "/" . $file;
                        $file_name = explode(".", $file);
                        $fileArr[] = [
                            'name' => (int)$file_name[0],
                            'url' => $filePath,
                            'ism3u8' => 1
                        ];
                    }
                }
                closedir($dh);
            }
            $v['fileurl'] = $fileArr;
        }
    }
    return $v;
}

function getVodByIdDetail($id)
{
    $v = Db::name('Vod')->where('vod_id', $id)->where('vod_status', 1)->find();
    if (empty($v)) {
        return [];
    }
    $v['playNames'] = getPlayerNames();
    $v['vod_time'] = date('Y-m-d H:i', $v['vod_time']);
    $v['vod_pic'] = strpos($v['vod_pic'], 'http') === 0 ? $v['vod_pic'] : (request()->domain() . '/' . $v['vod_pic']);

    $v['vod_content'] = strip_tags($v['vod_content']);
    $v['vod_pic_thumb'] = $v['vod_pic_thumb'] ? (strpos(
        $v['vod_pic_thumb'],
        'http'
    ) === 0 ? $v['vod_pic_thumb'] : (request()->domain() . '/' . $v['vod_pic_thumb'])) : '';
    $v['vod_actor'] = explode(',', $v['vod_actor']);
    $v['ism3u8'] = 1;
    return $v;
}

function getVodById($id)
{
    $v = Db::name('Vod')->where('vod_id', $id)->where('vod_status', 1)->find();
    if (empty($v)) {
        return [];
    }

    //分类
    $type_list = model('Type')->getCache('type_list');
    $playNames = getPlayerNames();
    $v['vod_time'] = date('Y-m-d H:i', $v['vod_time']);
    $v['vod_pic'] = strpos($v['vod_pic'], 'http') === 0 ? $v['vod_pic'] : (request()->domain() . '/' . $v['vod_pic']);
//        if($v['vod_rel_vod']){
//            $relIds = explode(',',$v['vod_rel_vod']);
//            $relIds = array_filter($relIds);
//            if(!empty($relIds)){
//                $v['vod_rel_list']=\db('vod')->whereIn('vod_id',$relIds)->field('vod_name,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time')->select();
//                if($v['vod_rel_list']->isEmpty()){
//                    $v['vod_rel_list']=[];
//                }
//            }
//        }
//        if(empty($v['vod_rel_list'])){
//            $v['vod_rel_list']=[];
//        }
    $v['vod_content'] = strip_tags($v['vod_content']);
    $v['vod_pic_thumb'] = $v['vod_pic_thumb'] ? (strpos(
        $v['vod_pic_thumb'],
        'http'
    ) === 0 ? $v['vod_pic_thumb'] : (request()->domain() . '/' . $v['vod_pic_thumb'])) : '';
    $v['vod_pic_slide'] = $v['vod_pic_slide'] ? (strpos(
        $v['vod_pic_slide'],
        'http'
    ) === 0 ? $v['vod_pic_slide'] : (request()->domain() . '/' . $v['vod_pic_slide'])) : '';

    if (!empty($v['type_id'])) {
        $v['type'] = $type_list[$v['type_id']];
        $v['type_1'] = $type_list[$v['type']['type_pid']];
    }
    //处理数据
    $v['vod_tag'] = explode(',', $v['vod_tag']);
    $v['vod_actor'] = explode(',', $v['vod_actor']);
    $playGroups = [];
    $v['play_group'] = [];
    $playfroms = explode('$$$', $v['vod_play_from']);
    if (count($playfroms) > 0) {
        unset($v['vod_play_from']);
        $playNotes = explode('$$$', $v['vod_play_note']);
        unset($v['vod_play_note']);
        unset($v['vod_play_server']);
        $playUrls = explode('$$$', $v['vod_play_url']);
        unset($v['vod_play_url']);
        foreach ($playUrls as $key => $jujiurl) {
            $from = $playNames[$playfroms[$key]];
            if ($from['status'] == 0) {
                continue;
            }
            if (strtolower($from['from']) === 'mahua' || strpos(strtolower($from['from']), 'm3u8') !== false) {
                $ism3u8 = 1;
            } else {
                $ism3u8 = 0;
            }
            $jujiurl = trim($jujiurl, '#');
            //解析url
            $jujis = explode('#', $jujiurl);
            $playList = [];
            foreach ($jujis as $juji) {
                list($name, $url) = explode('$', $juji);
                $playList[] = [
                    'name' => $name,
                    'url' => $url,
                    'ism3u8' => $ism3u8
                ];
            }
            $playGroups[$key] = [
                'sort' => $from['sort'],
                'playlist' => $playList,
                'from' => $from,
                'note' => $playNotes[$key]
            ];
        }

        $playGroups = array_values($playGroups);
        if (count($playGroups) == 1) {
            $v['play_group'][] = $playGroups[0];
        } else {
            usort(
                $playGroups,
                function ($a, $b) {
                    return $a['sort'] < $b['sort'] ? -1 : 1;
                }
            );
            $v['play_group'] = $playGroups;
        }
    }
    $v['haibao'] = cache("haibao_" . $id . "_" . count($playGroups[0]['playlist']));
    return $v;
}

function dingding_curl($dataArray, $url = '')
{
    if (empty($url)) {
        //默认千人群
        $url = "https://oapi.dingtalk.com/robot/send?access_token=1e1bd92eac6871e4ee749a104353811c664a941d7183aabde8eba8fc5e03ca98";
    }

    $post_string = json_encode($dataArray);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    //    curl_setopt($ch, CURLOPT_URL, 'https://oapi.dingtalk.com/robot/send?access_token=b1c479d6e4e041e83622d3d04aa2d77e6a296fe8ad633c485838ffdc3c3bd8c5');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json;charset=utf-8']);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // 线下环境不用开启curl证书验证, 未调通情况可尝试添加该代码
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $data = curl_exec($ch);
    curl_close($ch);


    return $data;
}

function sendDingding($message, $name, $isAtAll = false)
{
    if ($name == 'oss') {
        $name = 'oss上传下载通知';
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=e22b906c10cda7b3581ab6cc867d84ee7f87d61dc81bcc14db0ae23569a442f7';
    } elseif ($name === 'bjoss') {
        $name = '八戒 oss 上传下载通知';
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=e60614f4cb0cfef219376e1b21c69207985bced30ff17041fbbfcbe8dcfe947d';
    } elseif ($name == 'jpush') {
        $name = '极光消息点击通知';
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=0780f596e181d8330bb03ff95eb9a17e8fe664a488c83ccfe12a1586f9ef29d9';
    } elseif ($name == '天堂影视通知') {
        $name = '天堂影视抓取通知';
        $url = 'https://oapi.dingtalk.com/robot/send?access_token=ad1e8ad87d2ba5ea5ca3e3b2fb049aec79cd1c288334aeb1092a2057e3bd4e81';
    } elseif(strpos($name,'比尼')){
        $url="https://oapi.dingtalk.com/robot/send?access_token=22e02b5e1d858d589a4721b84ea7a8171209bada92882f6868cf71bdd8ffcfdb";
    } elseif(strpos($name,'品味')){
        $url="https://oapi.dingtalk.com/robot/send?access_token=de796e972c2946bc7a9bcf616633b755d11242a10657b32118ff09eb93b0676f";
    }elseif(strpos($name,'饭桌')){
        $url="https://oapi.dingtalk.com/robot/send?access_token=d84b8e94bc80bb0176e3b6e1deb24e4c640736dfb573f71af920dd0d4c211009";
    }  elseif($name==='updatedevice'){

        $name = '广告正常展示';
        $url="https://oapi.dingtalk.com/robot/send?access_token=a2189329557ad0d706e084e8a1430e9c976c8978b72c9875b3d9310aa5bbac00";
    } else {
        $url = '';
    }
    $at = [];
    if ($isAtAll === true) {
        $at['isAtAll'] = true;
    }

    if (is_array($isAtAll)) {
        $at['atMobiles'] = $isAtAll;
    }
    return dingding_curl(
        [
            "msgtype" => "text",
            "text" => [
                "content" => '[' . $name . ']' . $message,
            ],
            "at" => $at
        ],
        $url
    );
}

function getRecommandData($lp, $input)
{
    $order = $lp['order'];
    $by = $lp['by'];
    $type = $lp['type'];
    $ids = $lp['ids'];
    $rel = $lp['rel'];
    $paging = $lp['paging'];
    $pageurl = $lp['pageurl'];
    $level = $lp['level'];
    $area = $lp['area'];
    $lang = $lp['lang'];
    $state = $lp['state'];
    $wd = $lp['wd'];
    $tag = $lp['tag'];
    $class = $lp['class'];
    $letter = $lp['letter'];
    $actor = $lp['actor'];
    $director = $lp['director'];
    $version = $lp['version'];
    $year = $lp['year'];
    $start = intval(abs($lp['start']));
    $num = intval(abs($lp['num']));
    $half = intval(abs($lp['half']));
    $weekday = $lp['weekday'];
    $tv = $lp['tv'];
    $timeadd = $lp['timeadd'];
    $timehits = $lp['timehits'];
    $time = $lp['time'];
    $hitsmonth = $lp['hitsmonth'];
    $hitsweek = $lp['hitsweek'];
    $hitsday = $lp['hitsday'];
    $hits = $lp['hits'];
    $not = $lp['not'];
    $cachetime = $lp['cachetime'];
    $isend = $lp['isend'];
    $plot = $lp['plot'];
    $typenot = $lp['typenot'];

    $page = 1;
    $where = [];
    $totalshow = 0;

    if (empty($num)) {
        $num = 20;
    }
    if ($start > 1) {
        $start--;
    }

    if (!in_array($paging, ['yes', 'no'])) {
        $paging = 'no';
    }
    $param = [];
    $param['page'] = intval($input['page']) < 1 ? 1 : intval($input['page']);
    $param['ajax'] = intval($input['ajax']);
    $param['tid'] = intval($input['tid']);
    $param['mid'] = intval($input['mid']);
    $param['rid'] = intval($input['rid']);
    $param['pid'] = intval($input['pid']);
    $param['sid'] = intval($input['sid']);
    $param['nid'] = intval($input['nid']);
    $param['uid'] = intval($input['uid']);
    $param['level'] = intval($input['level']);
    $param['score'] = intval($input['score']);
    $param['limit'] = intval($input['limit']);
    $param['id'] = htmlspecialchars(urldecode(trim($input['id'])));
    $param['ids'] = htmlspecialchars(urldecode(trim($input['ids'])));
    $param['wd'] = htmlspecialchars(urldecode(trim($input['wd'])));
    $param['en'] = htmlspecialchars(urldecode(trim($input['en'])));
    $param['state'] = htmlspecialchars(urldecode(trim($input['state'])));
    $param['area'] = htmlspecialchars(urldecode(trim($input['area'])));
    $param['year'] = htmlspecialchars(urldecode(trim($input['year'])));
    $param['lang'] = htmlspecialchars(urldecode(trim($input['lang'])));
    $param['letter'] = htmlspecialchars(trim($input['letter']));
    $param['actor'] = htmlspecialchars(urldecode(trim($input['actor'])));
    $param['director'] = htmlspecialchars(urldecode(trim($input['director'])));
    $param['tag'] = htmlspecialchars(urldecode(trim($input['tag'])));
    $param['class'] = htmlspecialchars(urldecode(trim($input['class'])));
    $param['order'] = htmlspecialchars(urldecode(trim($input['order'])));
    $param['by'] = htmlspecialchars(urldecode(trim($input['by'])));
    $param['file'] = htmlspecialchars(urldecode(trim($input['file'])));
    $param['name'] = htmlspecialchars(urldecode(trim($input['name'])));
    $param['url'] = htmlspecialchars(urldecode(trim($input['url'])));
    $param['type'] = htmlspecialchars(urldecode(trim($input['type'])));
    $param['sex'] = htmlspecialchars(urldecode(trim($input['sex'])));
    $param['version'] = htmlspecialchars(urldecode(trim($input['version'])));
    $param['blood'] = htmlspecialchars(urldecode(trim($input['blood'])));
    $param['starsign'] = htmlspecialchars(urldecode(trim($input['starsign'])));
    $param['domain'] = htmlspecialchars(urldecode(trim($input['domain'])));
    if ($paging == 'yes') {
        $totalshow = 1;
        if (!empty($param['id'])) {
            //$type = intval($param['id']);
        }
        if (!empty($param['level'])) {
            $level = $param['level'];
        }
        if (!empty($param['ids'])) {
            $ids = $param['ids'];
        }
        if (!empty($param['tid'])) {
            $tid = intval($param['tid']);
        }
        if (!empty($param['year'])) {
            if (strlen($param['year']) == 4) {
                $year = intval($param['year']);
            } elseif (strlen($param['year']) == 9) {
                $s = substr($param['year'], 0, 4);
                $e = substr($param['year'], 5, 4);
                $s1 = intval($s);
                $s2 = intval($e);
                if ($s1 > $s2) {
                    $s1 = intval($e);
                    $s2 = intval($s);
                }

                $tmp = [];
                for ($i = $s1; $i <= $s2; $i++) {
                    $tmp[] = $i;
                }
                $year = join(',', $tmp);
            }
        }
        if (!empty($param['area'])) {
            $area = $param['area'];
        }
        if (!empty($param['lang'])) {
            $lang = $param['lang'];
        }
        if (!empty($param['tag'])) {
            $tag = $param['tag'];
        }
        if (!empty($param['class'])) {
            $class = $param['class'];
        }
        if (!empty($param['state'])) {
            $state = $param['state'];
        }
        if (!empty($param['letter'])) {
            $letter = $param['letter'];
        }
        if (!empty($param['version'])) {
            $version = $param['version'];
        }
        if (!empty($param['actor'])) {
            $actor = $param['actor'];
        }
        if (!empty($param['director'])) {
            $director = $param['director'];
        }
        if (!empty($param['wd'])) {
            $wd = $param['wd'];
        }
        if (!empty($param['by'])) {
            $by = $param['by'];
        }
        if (!empty($param['order'])) {
            $order = $param['order'];
        }
        if (!empty($param['page'])) {
            $page = intval($param['page']);
        }

        foreach ($param as $k => $v) {
            if (empty($v)) {
                unset($param[$k]);
            }
        }
        if (empty($pageurl)) {
            $pageurl = 'vod/type';
        }
        $param['page'] = 'PAGELINK';

        if ($pageurl == 'vod/type' || $pageurl == 'vod/show') {
            $type = intval($GLOBALS['type_id']);
            $type_list = model('Type')->getCache('type_list');
            $type_info = $type_list[$type];
            $flag = 'type';
            if ($pageurl == 'vod/show') {
                $flag = 'show';
            }
            $pageurl = mac_url_type($type_info, $param, $flag);
        } else {
            $pageurl = mac_url($pageurl, $param);
        }
    }

    $where['vod_status'] = ['eq', 1];
    if (!empty($ids)) {
        if ($ids != 'all') {
            $where['vod_id'] = ['in', explode(',', $ids)];
        }
    }
    if (!empty($not)) {
        $where['vod_id'] = ['not in', explode(',', $not)];
    }
    if (!empty($rel)) {
        $tmp = explode(',', $rel);
        if (is_numeric($rel) || mac_array_check_num($tmp) == true) {
            $where['vod_id'] = ['in', $tmp];
        } else {
            $where['vod_rel_vod'] = ['like', mac_like_arr($rel), 'OR'];
        }
    }
    if (!empty($level)) {
        if ($level == 'all') {
            $level = '1,2,3,4,5,6,7,8,9';
        }
        $where['vod_level'] = ['in', explode(',', $level)];
    }
    if (!empty($year)) {
        $where['vod_year'] = ['in', explode(',', $year)];
    }
    if (!empty($area)) {
        $where['vod_area'] = ['in', explode(',', $area)];
    }
    if (!empty($lang)) {
        $where['vod_lang'] = ['in', explode(',', $lang)];
    }
    if (!empty($state)) {
        $where['vod_state'] = ['in', explode(',', $state)];
    }
    if (!empty($version)) {
        $where['vod_version'] = ['in', explode(',', $version)];
    }
    if (!empty($weekday)) {
        //$where['vod_weekday'] = ['in',explode(',',$weekday)];
        $where['vod_weekday'] = ['like', mac_like_arr($weekday), 'OR'];
    }
    if (!empty($tv)) {
        $where['vod_tv'] = ['in', explode(',', $tv)];
    }
    if (!empty($timeadd)) {
        $s = intval(strtotime($timeadd));
        $where['vod_time_add'] = ['gt', $s];
    }
    if (!empty($timehits)) {
        $s = intval(strtotime($timehits));
        $where['vod_time_hits'] = ['gt', $s];
    }
    if (!empty($time)) {
        $s = intval(strtotime($time));
        $where['vod_time'] = ['gt', $s];
    }
    if (!empty($letter)) {
        if (substr($letter, 0, 1) == '0' && substr($letter, 2, 1) == '9') {
            $letter = '0,1,2,3,4,5,6,7,8,9';
        }
        $where['vod_letter'] = ['in', explode(',', $letter)];
    }
    if (!empty($type)) {
        if ($type == 'current') {
            $type = intval($param['tid']);
        }
        if ($type != 'all') {
            $tmp_arr = explode(',', $type);
            $type_list = model('Type')->getCache('type_list');
            $type = [];
            foreach ($type_list as $k2 => $v2) {
                if (in_array($v2['type_id'] . '', $tmp_arr) || in_array($v2['type_pid'] . '', $tmp_arr)) {
                    $type[] = $v2['type_id'];
                }
            }
            $type = array_unique($type);
            $where['type_id'] = ['in', implode(',', $type)];
        }
    }
    if (!empty($typenot)) {
        $where['type_id'] = ['not in', $typenot];
    }
    if (!empty($tid)) {
        $where['type_id|type_id_1'] = ['eq', $tid];
    }
    if (!in_array($GLOBALS['aid'], [13, 14, 15]) && !empty($param['id'])) {
        //$where['vod_id'] = ['not in',$param['id']];
    }

    if (!empty($hitsmonth)) {
        $tmp = explode(' ', $hitsmonth);
        if (count($tmp) == 1) {
            $where['vod_hits_month'] = ['gt', $tmp];
        } else {
            $where['vod_hits_month'] = [$tmp[0], $tmp[1]];
        }
    }
    if (!empty($hitsweek)) {
        $tmp = explode(' ', $hitsweek);
        if (count($tmp) == 1) {
            $where['vod_hits_week'] = ['gt', $tmp];
        } else {
            $where['vod_hits_week'] = [$tmp[0], $tmp[1]];
        }
    }
    if (!empty($hitsday)) {
        $tmp = explode(' ', $hitsday);
        if (count($tmp) == 1) {
            $where['vod_hits_day'] = ['gt', $tmp];
        } else {
            $where['vod_hits_day'] = [$tmp[0], $tmp[1]];
        }
    }
    if (!empty($hits)) {
        $tmp = explode(' ', $hits);
        if (count($tmp) == 1) {
            $where['vod_hits'] = ['gt', $tmp];
        } else {
            $where['vod_hits'] = [$tmp[0], $tmp[1]];
        }
    }

    if (in_array($isend, ['0', '1'])) {
        $where['vod_isend'] = $isend;
    }

    if (!empty($wd)) {
        $role = 'vod_name';
        if (!empty($GLOBALS['config']['app']['search_vod_rule'])) {
            $role .= '|' . $GLOBALS['config']['app']['search_vod_rule'];
        }
        $where[$role] = ['like', '%' . $wd . '%'];
    }
    if (!empty($tag)) {
        $where['vod_tag'] = ['like', mac_like_arr($tag), 'OR'];
    }
    if (!empty($class)) {
        $where['vod_class'] = ['like', mac_like_arr($class), 'OR'];
    }
    if (!empty($actor)) {
        $where['vod_actor'] = ['like', mac_like_arr($actor), 'OR'];
    }
    if (!empty($director)) {
        $where['vod_director'] = ['like', mac_like_arr($director), 'OR'];
    }
    if (in_array($plot, ['0', '1'])) {
        $where['vod_plot'] = $plot;
    }

    if ($GLOBALS['config']['app']['popedom_filter'] == 1) {
        $type_ids = mac_get_popedom_filter($GLOBALS['user']['group']['group_type']);
        if (!empty($type_ids)) {
            if (!empty($where['type_id'])) {
                $where['type_id'] = [$where['type_id'], ['not in', explode(',', $type_ids)]];
            } else {
                $where['type_id'] = ['not in', explode(',', $type_ids)];
            }
        }
    }
    if ($by == 'rnd') {
        $data_count = model('vod')->countData($where);
        $page_total = floor($data_count / $lp['num']) + 1;
        if ($data_count < $lp['num']) {
            $lp['num'] = $data_count;
        }
        $randi = @mt_rand(1, $page_total);
        $page = $randi;
        $by = 'hits_week';
        $order = 'desc';
    }

    if (!in_array(
        $by,
        [
            'id',
            'time',
            'time_add',
            'score',
            'hits',
            'hits_day',
            'hits_week',
            'hits_month',
            'up',
            'down',
            'level',
            'rnd'
        ]
    )) {
        $by = 'time';
    }
    if (!in_array($order, ['asc', 'desc'])) {
        $order = 'desc';
    }
    $order = 'vod_' . $by . ' ' . $order;
    $where_cache = $where;
    if (!empty($randi)) {
        unset($where_cache['vod_id']);
        $where_cache['order'] = 'rnd';
    }

    $cach_name = 'app_' . $GLOBALS['config']['app']['cache_flag'] . '_' . md5(
            'vod_listcache_' . http_build_query($where_cache) . '_' . $order . '_' . $page . '_' . $num . '_' . $start . '_' . $pageurl
        );
    $res = Cache::get($cach_name);
    if (empty($cachetime)) {
        $cachetime = $GLOBALS['config']['app']['cache_time'];
    }
    if ($GLOBALS['config']['app']['cache_core'] == 0 || empty($res)) {
        $res = model('vod')->listData(
            $where,
            $order,
            $page,
            $num,
            $start,
            'vod_year,vod_name,image_down,vod_pic,vod_pic_thumb,vod_pic_slide,vod_blurb,vod_remarks,vod_id,vod_level,vod_actor,vod_class,vod_time',
            1,
            $totalshow
        );
        if ($GLOBALS['config']['app']['cache_core'] == 1) {
            Cache::set($cach_name, $res, $cachetime);
        }
    }
    $res['pageurl'] = $pageurl;
    $res['half'] = $half;

    foreach ($res['list'] as &$litem) {
        if ($litem['image_down'] > 0) {
            $litem['vod_pic'] = 'http://7dfjeh.aojiasen.cn/cover/' . $litem['vod_id'] . '.jpg';
        }
    }

    return $res['list'];
}

function selfDump()
{
    ob_start();
    $args = func_get_args();
    if (IS_CLI) {
        var_export(date('Y-m-d H:i:s') . '-' . microtime(true));
        foreach ($args as $arg) {
            echo json_encode($arg, JSON_UNESCAPED_UNICODE);
        }
        echo "\n\r";
    } else {
        dump(date('Y-m-d H:i:s') . '-' . microtime(true));
        foreach ($args as $arg) {
            dump($arg);
        }
    }
    ob_flush();
    ob_end_flush();
}

function fget_contents()
{
    $args = func_get_args();
    // the @ can be removed if you lower error_reporting level
    $contents = @call_user_func_array('file_get_contents', $args);

    if ($contents === false) {
        return false;
    } else {
        return $contents;
    }
}

function get_exname($file_name)
{
    if (empty($file_name))
        return false;

    $file_name = strtolower($file_name);
    $rev_str = strrev($file_name);
    $ex_name_len = strpos($rev_str, '.');  //扩展名的长度
    $file_name_len = strlen($file_name);
    $ex_name = substr($file_name, $file_name_len - $ex_name_len);

    return $ex_name;
}

function curl_get_file_contents($URL,$headers=null,$agent=null)
{
    $c = curl_init();
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($c, CURLOPT_TIMEOUT, 5);

    if ($headers && !empty($headers)) {
        curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
    }
    //curl_setopt($c, CURLOPT_HEADER, 1);//输出远程服务器的header信息
    curl_setopt($c, CURLOPT_USERAGENT, !empty($agent)?$agent:'Mozilla/5.0 (iPhone; CPU iPhone OS 14_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148');
    curl_setopt($c, CURLOPT_URL, $URL);
    $contents = curl_exec($c);
    curl_close($c);
    if ($contents) {
        return $contents;
    } else {
        return FALSE;
    }
}

function addLog($appId,$deviceId,$points,$memo,$type,$date,$time_added){
    \db('points')->insertGetId([
       'app_id'=> $appId,
        'device_id'=>$deviceId,
        'points'=>$points,
        'memo'=>$memo,
        'type'=>$type,
        'date'=>$date,
        'time_added'=>$time_added
    ]);
    \db('device')->where('app_id',$appId)->where('device_id',$deviceId)->setInc('points',$points);
}


function dealDeviceDate($item){
    $item['date']=date('Y-m-d');
    $exist = db('device_date')->where('app_id', $item['app_id'])->where('device_id', $item['device_id'])->where('date', $item['date'])->find();
    if(empty($exist)) {
        $deviceInfo = db('device')->where('device_id', $item['device_id'])->where('app_id', $item['app_id'])->find();
        $signTime = strtotime(date('Y-m-d', $deviceInfo['time_added']));
        $item['sign_days'] = round((strtotime('tomorrow') - $signTime) / 3600 / 24);
        $insertArray = [
            "kaiping_num" => 0,
            "quanping_num" => 0,
            "jili_num" => 0,
            "zhibo_num" =>0,
            "vod_num" => 0,
            "app_id"=>$item['app_id'],
            "device_id"=>$item['device_id'],
            "app_name"=>$item['app_name'],
            "device_name"=>$item['device_name'],
            "date"=>$item['date'],
            "sign_days"=>$item['sign_days']
        ];
//        {"app_id":"A6153279862574","device_id":"00035aaceb1641fa868cbd609deaf006","app_name":"比尼影视安卓","device_name":"HUAWEI","kaiping_num":"2","quanping_num":"1","jili_num":"0","zhibo_num":"0","vod_num":"2","date":"2021-01-27","sign_days":4}

        try {
          $id =  db('device_date')->insertGetId($insertArray);
        } catch (Exception $e) {
        }
    }
    $data=[];
    $model = db('device_date')->where('app_id', $item['app_id'])->where('device_id', $item['device_id'])->where('date', $item['date']);
    $update = false;
    if($item['adtype']==1){
        $model->inc('kaiping_num');
        $update = true;
    }
    if($item['adtype']==2 && $item['is_show']===true){
        $model->inc('quanping_num');
        $update = true;
    }

    if($item['adtype']==3 && $item['is_show']===true){
        $model->inc('jili_num');
        $update = true;
    }
    if($update) {
        $model->update();
    }

    return db('device_date')->where('app_id', $item['app_id'])->where('device_id', $item['device_id'])->where('date', $item['date'])->find();

}